package com.erd.datacollect.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpAPIService {
  private static final String CONTENT_TYPE_TEXT_JSON = "text/json";

  private static final RequestConfig requestConfig = RequestConfig.custom()
      .setConnectTimeout(5000)
      .setSocketTimeout(10000).build();

  /**
   * GET请求  参数携带在url中
   *
   * @param url
   * @return
   */
  public static String executeGet(String url,Map<String,String> headers){
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(url);
    if(headers!=null){
      for(String key:headers.keySet()){
        httpGet.setHeader(key,headers.get(key).toString());
      }
    }
    httpGet.setConfig(requestConfig);
    CloseableHttpResponse response = null;
    String result = null;

    try {
      response = httpClient.execute(httpGet);

      HttpEntity entity = response.getEntity();
      if (entity != null) {
        result = EntityUtils.toString(entity, "UTF-8");
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        response.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    return result;
  }
  public static String executeGet(String url) {
    return executeGet(url,null);
  }

  /**
   * POST请求 带参数 不支持json
   *
   * @param url 请求地址
   * @param map 参数
   * @return
   */
  public static String executePost(String url, Map<String, Object> map) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    List<NameValuePair> params = new ArrayList<>();
    for (Map.Entry<String, Object> entry : map.entrySet()) {
      params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
    }
    UrlEncodedFormEntity entity = null;
    String result = null;
    try {
      entity = new UrlEncodedFormEntity(params, "UTF-8");
      HttpPost httpPost = new HttpPost(url);
      httpPost.setConfig(requestConfig);
      httpPost.setEntity(entity);
      CloseableHttpResponse response = httpClient.execute(httpPost);

      HttpEntity httpEntity = response.getEntity();
      result = EntityUtils.toString(httpEntity, "UTF-8");
    } catch (IOException e) {
      e.printStackTrace();
    }finally {
      try {
        httpClient.close();
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
    return result;
  }
  /**
   * 不支持json
   * */
  public static String executePost(String url, String message){
    return executePost(url,message,null);
  }
  /**
   * 不支持json
   * */
  public static String executePost(String url,String message,Map<String,String> headers){
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);
    if(headers!=null){
     for(String key:headers.keySet()){
       httpPost.setHeader(key,headers.get(key).toString());
     }
    }
    String result = null;
    try {
      CloseableHttpResponse httpResponse;
      httpPost.setHeader("Content-type", "application/json");
      // 构建JSON数据
      StringEntity entity = null;
      entity = new StringEntity(message);
      httpPost.setEntity(entity);
      // 执行POST请求
      httpResponse = httpClient.execute(httpPost);
      // 处理响应结果
      HttpEntity httpEntity = httpResponse.getEntity();
      result = EntityUtils.toString(httpEntity, "UTF-8");
      if(httpResponse!=null){
        httpResponse.close();
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }finally {
      try {
        httpClient.close();
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
    return result;
  }

  /**
   * POST请求   不带参数 不支持json
   *
   * @param url
   * @return
   */
  public static String executePost(String url) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);
    httpPost.setConfig(requestConfig);
    CloseableHttpResponse response = null;
    String result = null;
    try {
      response = httpClient.execute(httpPost);

      HttpEntity entity = response.getEntity();
      result = EntityUtils.toString(entity, "UTF-8");
    } catch (Exception e) {
      e.printStackTrace();
    }finally {
      try {
        httpClient.close();
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
    return result;
  }

  public static String executeDelete(String url){
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpDelete httpDelete = new HttpDelete(url);
    httpDelete.setConfig(requestConfig);
    CloseableHttpResponse response = null;
    String result = null;
    try {
      response = httpClient.execute(httpDelete);

      HttpEntity entity = response.getEntity();
      result = EntityUtils.toString(entity, "UTF-8");
    } catch (Exception e) {
      e.printStackTrace();
    }finally {
      try {
        httpClient.close();
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
    return result;
  }
  /**
   * POST请求   携带Json格式的参数
   *
   * @param url
   * @param param
   * @return
   * @throws IOException
   */
  public static String postJson(String url, Object param) {
    return postJson(url,param,null);
  }
  public static String postJson(String url, Object param,String token) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    String result = null;
    HttpPost httpPost = new HttpPost(url);
    if(token!=null){
      httpPost.setHeader("Authorization",token);
    }
    httpPost.setConfig(requestConfig);
    StringEntity se = null;
    try {
      String parameter = objToJson(param);
      se = new StringEntity(parameter,"utf-8");
     se.setContentEncoding("UTF-8");
     se.setContentType("application/json");
      httpPost.setEntity(se);
      response = httpClient.execute(httpPost);
      HttpEntity httpEntity = response.getEntity();
      result = EntityUtils.toString(httpEntity, "UTF-8");
      response.close();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }catch (JsonProcessingException e){
      e.printStackTrace();
    }catch (IOException e) {
      e.printStackTrace();
    }finally {
      try {
        httpClient.close();
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
    return result;
  }
  private static String objToJson(Object obj)throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    String str = "";
    str=mapper.writeValueAsString(obj);
    return str;
  }
}
